package com.project.api.sale.service;

import com.project.api.sale.dao.AttributeDao;
import com.project.api.sale.dao.ProductDao;
import com.project.api.sale.dao.UserDao;
import com.project.api.sale.dao.BuyCarDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService  {
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;
    @Autowired
    private ProductService productService;
    public UserDao getUser(int id){
        UserDao dao = null;
        String find = "select * from user where id = ?";
        try {
            dao = (UserDao)mainJdbcTemplate.queryForObject(
                    find, new Object[] { id },new BeanPropertyRowMapper(UserDao.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            dao=new UserDao();
        }
        return dao;
    }
    /**
     * 插入并获取id
     * @param openid
     * @return
     */
    public int create(String openid) {
        UserDao dao = null;
        String find = "select * from user where openid = ?";
        try {
            dao = (UserDao)mainJdbcTemplate.queryForObject(
                    find, new Object[] { openid },new BeanPropertyRowMapper(UserDao.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            dao=null;
        }
        if(dao==null){
            String sql = "insert into user(openid,createTime) values(?,?)";
            KeyHolder keyHolder = new GeneratedKeyHolder();
            mainJdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                    ps.setString(1, openid);
                    ps.setLong(2,System.currentTimeMillis());
                    return ps;
                }
            }, keyHolder);
            return keyHolder.getKey().intValue();
        }else{
            return dao.getId();
        }
    }
    public int createBuyCar(int userId,int productId,String attributeId,int qty){
        BuyCarDao dao = null;
        String find = "select * from buycar where attributeId = ? and userId= ? and productId = ?";
        try {
            dao = (BuyCarDao)mainJdbcTemplate.queryForObject(
                    find, new Object[] { attributeId,userId,productId },new BeanPropertyRowMapper(BuyCarDao.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            dao=null;
        }
        if(dao!=null){
            int id=dao.getId();
            int q=dao.getQty();
            q+=qty;
            String sql="update buycar set qty= ?  where id = ?";
            return mainJdbcTemplate.update(sql, q,id);
        }else {
            String sql = "insert into buycar(userId,productId,attributeId,qty) values(?,?,?,?)";
            return mainJdbcTemplate.update(sql, userId, productId, attributeId, qty);
        }
    }

    public int reg(int id,String name,String phone,String prov,String city,String district,String address){
        String sql="update user set name= ?,phone=?,province=?,city=?,dist=?,address=?  where id = ?";
        return mainJdbcTemplate.update(sql, name,phone,prov,city,district,address,id);
    }
    public int deleteBuyCar(int userId,int id){
        String sql="delete from buycar  where id = ? and userId= ?";
        return mainJdbcTemplate.update(sql, id,userId);
    }
    public List<BuyCarDao> getBuyCar(int userId){
        String sql = "select * from buycar where userId=?";
        List<BuyCarDao> daoLists  = null;
        try {
            daoLists = mainJdbcTemplate.query(sql,new Object[] { userId },
                    new BeanPropertyRowMapper(BuyCarDao.class));
        } catch (EmptyResultDataAccessException e) {
            daoLists= new ArrayList();
        }
        for (int i =0 ;i<daoLists.size();i++){
            BuyCarDao dao=daoLists.get(i);
            int productId=dao.getProductId();
            ProductDao productDao=productService.getProductById(productId);
            dao.setProduct(productDao);
            String attribute=dao.getAttributeId();
            String[] attr=attribute.split(",");
            StringBuffer attributeStr=new StringBuffer();
            for (int k=0;k<attr.length;k++){
                if(attr[k]==null||attr[k].equalsIgnoreCase("")){
                    continue;
                }
                int a=Integer.parseInt(attr[k]);
                AttributeDao attributeDao=productService.getAttributeById(a);
                if(attributeDao.getId()!=0){
                    attributeStr.append("(");
                    attributeStr.append(attributeDao.getPinlei().getName());
                    attributeStr.append(")");
                    attributeStr.append(attributeDao.getName());
                    attributeStr.append(";");
                }
            }
            dao.setAttrStr(attributeStr.toString());
            daoLists.set(i,dao);
        }
        return daoLists;
    }

    public BuyCarDao getBuyCarById(int id){
        String sql = "select * from buycar where id=?";
        BuyCarDao dao  = null;
        try {
            dao = (BuyCarDao) mainJdbcTemplate.queryForObject(sql,new Object[] { id },
                    new BeanPropertyRowMapper(BuyCarDao.class));
        } catch (EmptyResultDataAccessException e) {
            dao= new BuyCarDao();
        }
        int productId=dao.getProductId();
        ProductDao productDao=productService.getProductById(productId);
        dao.setProduct(productDao);
        String attribute=dao.getAttributeId();
        String[] attr=attribute.split(",");
        StringBuffer attributeStr=new StringBuffer();
        for (int i=0;i<attr.length;i++){
            String val=attr[i];
            if(val==null||val.equalsIgnoreCase("")){
                continue;
            }
            int a=Integer.parseInt(val);
            AttributeDao attributeDao=productService.getAttributeById(a);
            if(attributeDao.getId()!=0){
                attributeStr.append("(");
                attributeStr.append(attributeDao.getPinlei().getName());
                attributeStr.append(")");
                attributeStr.append(attributeDao.getName());
                attributeStr.append(";");
            }
        }
        dao.setAttrStr(attributeStr.toString());
        return dao;
    }
}
